package com.fuping;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.stage.DirectoryChooser;

public class MainContorller {

	@FXML
	private Button btn_load;
	@FXML
	private Button btn_search;

	@FXML
	private TableView<Command> tableView;

	@FXML
	private TableColumn<Command, String> fileColumn;

	@FXML
	private TextField dirPath;

	@FXML
	private TextField searchText;
	@FXML
	private TextField typeText;
	private String filePath;
	private String searchStr;
	private String searchType;

	private static Map<String,String> map ;
	@FXML
	private void initialize() {

		loadProperties();
		fileColumn.setCellValueFactory(cellData -> cellData.getValue().pathProperty());
		
		tableView.setRowFactory(tv -> {// 双击打开文件
			TableRow<Command> row = new TableRow<Command>();
			row.setOnMouseClicked(event -> {
				if (!row.isEmpty() && event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
					Command command = row.getItem();
					String[] cmd = null;
					if (command.getPath().toLowerCase().endsWith(".class")
							|| command.getPath().toLowerCase().endsWith(".jar")) {
						cmd = new String[] {map.get("class"), command.getPath() };
					} else {
						cmd = new String[] {map.get("txt"), command.getPath() };
					}

					exec(cmd);
				} else if ((!row.isEmpty() && event.getButton() == MouseButton.SECONDARY
						&& event.getClickCount() == 1)) {//右键选中复制到剪贴板
					Command command = row.getItem();
					Clipboard clipboard = Clipboard.getSystemClipboard();
					ClipboardContent content = new ClipboardContent();
					content.putString(command.getPath());
					clipboard.setContent(content);
				}
			});
			return row;
		});
	}

	@FXML
	private void btnLoadAction(ActionEvent event) {

		String cwd = System.getProperty("user.dir");
		File file = new File(cwd);
		DirectoryChooser chooser = new DirectoryChooser();
		chooser.setInitialDirectory(file);
		File chosenDir = chooser.showDialog(null);
		if (chosenDir != null) {
			dirPath.setText(chosenDir.getAbsolutePath());
		} else {
			return;
		}
	}

	@FXML
	private void btnSearchAction(ActionEvent event) {

		filePath = dirPath.getText();
		searchStr = searchText.getText();
		searchType = typeText.getText();
		tableView.getItems().clear();
		btn_search.setDisable(true);

		btn_load.setDisable(true);
		doWork();
	}

	private void doWork() {
		Executor exec = Executors.newFixedThreadPool(10, runnable -> {

			Thread t = new Thread(runnable);
			t.setDaemon(true);
			return t;
		});
		Task<List<Command>> task = new Task<List<Command>>() {
			@Override
			protected List<Command> call() throws Exception {
				StringBuffer sb = new StringBuffer();
				sb.append(" *.");
				sb.append(searchType);
				String[] cmd = { "cmd", "/C", "findstr /s /m /i " + searchStr  + sb.toString() };
				Runtime r = Runtime.getRuntime();
				File file = new File(filePath);
				Process p = null;
				List<Command> commandLt = new ArrayList<>();
				try {
					p = r.exec(cmd, null, file);
					BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), "gbk"));
					String line = null;
					while ((line = br.readLine()) != null) {
						commandLt.add(new Command(filePath + File.separator + new String(line)));

					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					
				}
				return commandLt;
			}

			@Override
			protected void succeeded() {
				tableView.getItems().clear();
				tableView.getItems().addAll(getValue());
				showAlert(AlertType.INFORMATION, "提示", "任务完成");
				btn_search.setDisable(false);

				btn_load.setDisable(false);
			}
		};
		exec.execute(task);
	}

	private void exec(String[] cmd) {
		Runtime r = Runtime.getRuntime();
		try {
			r.exec(cmd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void showAlert(AlertType type, String title, String message) {
		Alert alert = new Alert(type);
		alert.setTitle(title);
		alert.setHeaderText(null);
		alert.setContentText(message);

		alert.showAndWait();
	}
	
	
	private static Map<String,String> loadProperties() {

		map = new HashMap<>();
		InputStream in = ClassLoader
				.getSystemResourceAsStream("config.properties");
		Properties p = new Properties();
		try {
			p.load(in);
			Enumeration<Object> e = p.keys();
			if (e.hasMoreElements()) {
				map.put("txt", p.getProperty("txt"));
				map.put("class", p.getProperty("class"));
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			map = null;
		}
		return map;

	}


}
